import React from 'react'
import { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from 'react'
import { CaretDownOutlined, CaretUpOutlined } from '@ant-design/icons'
import { Breakpoint, Button, Col, Form, Grid, Row, Space } from 'antd'
import { FormItem } from './formTypes'
import styles from './index.module.less'
import { RenderFormItem } from './partials/RenderFormItem'
// import { useHistory } from 'react-router-dom';

const { useBreakpoint } = Grid
interface SearchFormProps {
  fields: FormItem[]
  query: (value: any) => void
  labelWidth?: number
  screenCountList?: {
    screen: string
    count: number
  }[]
  screenConfig?: {
    [key: string]: number
  }
  urlParams?: {
    [key: string]: any
  }
}

const screens: Breakpoint[] = ['xxl', 'xl', 'lg', 'md', 'sm', 'xs']

const getNowScreen = (screenMap: Partial<Record<Breakpoint, boolean>>) => {
  for (let i = 0; i < screens.length; i++) {
    if (screenMap[screens[i]]) return screens[i]
  }
}

const screenDefaultConfig = {
  xxl: 5,
  xl: 6,
  lg: 8,
  md: 12,
  sm: 12,
  xs: 24
}

const getKey = (item: FormItem, index: number) => {
  const name = item.formItemProps?.name?.toString()
  return name ?? index
}

export const SearchForm = forwardRef(
  ({ fields = [], query, urlParams, screenConfig = screenDefaultConfig, labelWidth = 86 }: SearchFormProps, ref) => {
    // const history = useHistory();
    const screenMap = useBreakpoint()
    const [screen, setScreen] = useState<Breakpoint>('xxl')
    const [visible, setVisible] = useState(false)
    const [expand, setExpand] = useState(false)
    const [form] = Form.useForm()

    useEffect(() => {
      const nowScreen = getNowScreen(screenMap)
      nowScreen && setScreen(nowScreen)
    }, [screenMap])

    useEffect(() => {
      const needShowCount = 24 / screenConfig[screen] - 1 || 1
      setVisible(Math.round(needShowCount) < fields.length)
    }, [screen])

    const getFields = (fields: FormItem[]) => {
      if (expand) {
        return fields.map((field, index) => (
          <Col key={getKey(field, index)} {...screenConfig} {...field.span}>
            <RenderFormItem config={field} />
          </Col>
        ))
      }
      const needShowCount = 24 / screenConfig[screen] - 1 || 1
      return fields.map((field, index) => {
        if (index < needShowCount) {
          return (
            <Col key={getKey(field, index)} {...screenConfig} {...field.span}>
              <RenderFormItem config={field} />
            </Col>
          )
        } else {
          return (
            <RenderFormItem
              key={getKey(field, index)}
              config={{ ...field, formItemProps: { ...field.formItemProps, hidden: true } }}
            />
          )
        }
      })
    }

    useEffect(() => {
      form.resetFields()
      form.setFieldsValue(urlParams)
    }, [urlParams])

    const onFinish = (values: any) => {
      query(values)
    }

    useImperativeHandle(ref, () => ({
      onExpand: () => {
        setExpand(true)
      }
    }))

    return (
      <Form
        className={styles['search-form-container']}
        form={form}
        onFinish={onFinish}
        autoComplete="off"
        labelCol={{ style: { width: labelWidth } }}
      >
        <Row>
          {getFields(fields)}
          <Col style={{ textAlign: 'right', flex: 1 }}>
            <Space style={{ marginBottom: 12 }}>
              {visible && (
                <span
                  style={{
                    display: 'inline-block',
                    minWidth: 36,
                    fontSize: 12,
                    color: 'var(--xdrsec-highlight-color)',
                    cursor: 'pointer'
                  }}
                  onClick={() => {
                    setExpand(!expand)
                  }}
                >
                  {expand ? (
                    <>
                      收起
                      <CaretUpOutlined />
                    </>
                  ) : (
                    <>
                      展开
                      <CaretDownOutlined />
                    </>
                  )}
                </span>
              )}
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button
                onClick={() => {
                  form.resetFields()
                  // history.push({
                  //   pathname: history.location.pathname,
                  //   search: ``,
                  // });
                }}
              >
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </Form>
    )
  }
)
